package jmu.zzh.alumnus.user.service;

import cn.hutool.core.bean.BeanUtil;
import jakarta.validation.Valid;
import jmu.zzh.alumnus.common.exception.NotAdminException;
import jmu.zzh.alumnus.common.exception.PasswordErrorException;
import jmu.zzh.alumnus.common.exception.UserNotExistsException;
import jmu.zzh.alumnus.common.util.SnowflakeUtil;
import jmu.zzh.alumnus.common.util.CustomJWTUtils;
import jmu.zzh.alumnus.user.entity.User;
import jmu.zzh.alumnus.user.entity.UserExample;
import jmu.zzh.alumnus.common.exception.UserAlreadyExistsException;
import jmu.zzh.alumnus.user.mapper.UserMapper;
import jmu.zzh.alumnus.user.request.LoginRequest;
import jmu.zzh.alumnus.user.response.LoginResponse;
import jmu.zzh.alumnus.user.request.UserRequest;
import jmu.zzh.alumnus.user.request.UpdatePasswordRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    CustomJWTUtils customJWTUtils;

    public long count(){
        return userMapper.countByExample(null);
    }

    public int register(UserRequest userRequest){
        // 去数据库查询 username 是否存在
        String username = userRequest.getUsername();
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        boolean empty = users.isEmpty();
        if(!empty){
            throw new UserAlreadyExistsException("该用户名已被注册");
        }

        User user = new User();
        // 设置基本信息
        Long id = SnowflakeUtil.getId();
        user.setId(id);
        user.setAlumniId(id);
        user.setUsername(username);
        user.setPassword(userRequest.getPassword());
        user.setName(userRequest.getName());
        user.setGender(userRequest.getGender());
        user.setBirthDate(userRequest.getBirthDate());
        user.setStudentId(userRequest.getStudentId());
        
        // 设置学校信息
        user.setEnrollYear(userRequest.getEnrollYear());
        user.setGraduateYear(userRequest.getGraduateYear());
        user.setCollegeCode(userRequest.getCollegeCode());
        user.setMajorCode(userRequest.getMajorCode());
        user.setClassCode(userRequest.getClassCode());
        
        // 设置当前情况
        user.setMobile(userRequest.getMobile());
        user.setEmail(userRequest.getEmail());
        user.setIndustry(userRequest.getIndustry());
        user.setWorkUnit(userRequest.getWorkUnit());
        
        // 设置默认为非管理员
        user.setAdmin(false);

        return userMapper.insert(user);
    }

    public LoginResponse login(@Valid LoginRequest request, boolean isAdminLogin) {
        String username = request.getUsername();
        String password = request.getPassword();

        // 验证用户名是否存在
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);

        if (users.isEmpty()) {
            throw new UserNotExistsException("用户名不存在");
        }

        // 验证密码是否正确
        User user = users.get(0);
        if (!user.getPassword().equals(password)) {
            throw new PasswordErrorException("密码错误");
        }

        // 生成token
        String token = customJWTUtils.createToken(user.getUsername(), user.getPassword(), user.getAlumniId());

        LoginResponse response = new LoginResponse();
        response.setAlumniId(user.getAlumniId());
        response.setUsername(user.getUsername());
        response.setIsAdmin(user.getAdmin());
        response.setToken(token);

        // 如果是管理员登录，验证是否是管理员
        if (isAdminLogin && !Boolean.TRUE.equals(user.getAdmin())) {
            System.out.println(user.getAdmin());
            throw new NotAdminException("该账号不是管理员账号，无法登录后台");
        }

        return response;
    }

    public User getCurrentUser(String username) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(example);
        if (users.isEmpty()) {
            throw new UserNotExistsException("用户不存在");
        }
        return users.get(0);
    }

    public int updateUserInfo(String username, User updateUser) {
        User currentUser = getCurrentUser(username);
        
        // 只更新允许修改的字段
        currentUser.setName(updateUser.getName());
        currentUser.setMobile(updateUser.getMobile());
        currentUser.setEmail(updateUser.getEmail());
        currentUser.setGraduateYear(updateUser.getGraduateYear());
        currentUser.setMajorCode(updateUser.getMajorCode());
        currentUser.setWorkUnit(updateUser.getWorkUnit());
        currentUser.setIndustry(updateUser.getIndustry());
        
        return userMapper.updateByPrimaryKey(currentUser);
    }

    public int updatePassword(String username, UpdatePasswordRequest request) {
        User user = getCurrentUser(username);
        
        // 验证原密码
        if (!user.getPassword().equals(request.getOldPassword())) {
            throw new PasswordErrorException("原密码错误");
        }
        
        // 更新密码
        user.setPassword(request.getNewPassword());
        return userMapper.updateByPrimaryKey(user);
    }
}
